// void, Obj This

Hero this;
Unit u;
int nDetachDistance, nDetachDistanceEngage, nRecallDistance;
int i, distance, v;

Sleep(rand(50)+30);

nDetachDistance = GetConst("DetachDistance");
nDetachDistanceEngage = GetConst("DetachDistanceEngage");
nRecallDistance = GetConst("RecallDistance");

this = This.AsHero;
if(!.IsValid) return;
if(.IsHeirOf("CaptainOutpost"))
	nDetachDistance += 4000;
	
while(.IsValid){

	if (IsAIPlayer(.player))
	{
		Sleep(20 * 1000);
		continue;
	}
	v = 0;
	.army.ClearDead;
	for(i=0; i<.army.count; i+=1) {
		u = .army[i].AsUnit;
		if( u.IsValid ) {
			distance = Dist(.posRH, u.posRH);
			if(u.command == "approach") {
				continue;
			} else if( 
				u.command != "engage" && 
				u.command != "engage_unit_type" &&
				u.command != "attack" && 
				u.command != "attack_unit_type" && 
				u.command != "capture" &&
				u.command != "getitems"
				) {
				if( distance > nDetachDistance ) {
					if( u.command == "idle" )
						u.SetCommand("attach", this);
					else
						u.AddCommand(false, "attach", this);
					if(!.InShip() && !u.InShip())
					if(!.GetHolderSett.GetCentralBuilding.IsHeirOf("BaseShipyard"))
					if(!u.GetHolderSett.GetCentralBuilding.IsHeirOf("BaseShipyard"))
						u.DetachFrom(this);
				} else if( distance > nDetachDistanceEngage ){
					if(.command == "engage"){
						if(u.command == "stand_position" 
						|| u.command == "idle"){
							Sleep(rand(200)+100);
							u.SetCommand("approach_hero", this);
							u.AddCommand(false, "engage");
						}
					}
				}
			} else {
				if(.command == "capture"){
					if( distance > 800 ){
						Sleep(rand(200)+100);
						u.SetCommand("approach_hero", this);
						if(.HasItem("irage_battle") || 
							.HasItem("ibattle") ||
							.HasItem("ibattle_stand") ||
							.HasItem("irage_battle_stand"))
							u.AddCommand(false, "engage");
					}
				} else {
					if( distance > nDetachDistanceEngage ){
						Sleep(rand(200)+100);
						if(.command != "retreat_notai" &&
							.command != "retreat_bld_notai"){
							u.SetCommand("approach_hero", this);
							if(.HasItem("irage_battle") || 
								.HasItem("ibattle") ||
								.HasItem("ibattle_stand") ||
								.HasItem("irage_battle_stand"))
								u.AddCommand(false, "engage");
						}
					}

				}
			}
			if(!u.IsVisible){
				v+=1;
			}
		}
		
		Sleep(30);
	}
	.army.ClearDead;
	if(.HasArmy){
		if(!.InHolder)
		if(.army.count == v){
			if(.IsVisible)
				.SetVisible(false);
		} else {
			if(!.IsVisible)
				.SetVisible(true);
		}
	} else {
		if(!.IsVisible)
			.SetVisible(true);
			Sleep(10000);
	}
	
	Sleep(917+rand(300));
}